﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Diagnostics;
using Microsoft.Web.Media.SmoothStreaming;

namespace UCCLIGHT2.Player
{
    public partial class Player : UserControl
    {
       DispatcherTimer timer;
       public Player()
        {
            InitializeComponent();
            GetMediaInfomation();
            SetEvents();
            SetTimer();
        }

        private void GetMediaInfomation()
        {   
            //임시-------------------------------------------------------------------------------------------------------
            //mediaElement.Source = new Uri("http://61.34.4.33/media/Big Buck Bunny.wmv", UriKind.RelativeOrAbsolute);
            mediaElement.SmoothStreamingSource = new Uri("http://61.34.4.33/media/Big Buck Bunny.ism/Manifest", UriKind.RelativeOrAbsolute);
            //------------------------------------------------------------------------------------------------------------
        }

        private void SetEvents()
        {          
            this.btnGetSource.Click += new RoutedEventHandler(btnGetSource_Click);
            this.btnPlay.Click += new RoutedEventHandler(btnPlay_Click);
            this.btnStop.Click += new RoutedEventHandler(btnStop_Click);
            this.btnVolume.Click += new RoutedEventHandler(btnVolume_Click);
            this.btnFullScreen.Click += new RoutedEventHandler(btnFullScreen_Click);
            this.mediaElement.MediaOpened += new RoutedEventHandler(mediaElement_MediaOpened);
            this.mediaElement.DownloadProgressChanged += new RoutedEventHandler(mediaElement_DownloadProgressChanged);
            this.seekGrid.MouseLeftButtonDown += new MouseButtonEventHandler(seekGrid_MouseLeftButtonDown);
            this.mediaElement.MediaEnded += new RoutedEventHandler(mediaElement_MediaEnded);
            this.mediaElement.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>(mediaElement_MediaFailed);
            this.mediaInfomationGrid.MouseEnter += new MouseEventHandler(mediaInfomationGrid_MouseEnter);
            this.mediaInfomationGrid.MouseLeave += new MouseEventHandler(mediaInfomationGrid_MouseLeave);
            this.controlGrid.MouseEnter += new MouseEventHandler(controlGrid_MouseEnter);
            this.controlGrid.MouseLeave += new MouseEventHandler(controlGrid_MouseLeave);
            Application.Current.Host.Content.FullScreenChanged += new EventHandler(FullScreenChanged);
            this.sliderVolume.ValueChanged += new RoutedPropertyChangedEventHandler<double>(sliderVolume_ValueChanged);
        }        

        void controlGrid_MouseLeave(object sender, MouseEventArgs e)
        {
            if (Application.Current.Host.Content.IsFullScreen)
            {
                this.ControlGrid_HiddenStoryboard.Begin();
                this.mediaElement.Margin = new Thickness(0, 30, 0, 0);
            }
        }

        void controlGrid_MouseEnter(object sender, MouseEventArgs e)
        {
            if (Application.Current.Host.Content.IsFullScreen)
            {
                this.ControlGrid_VisibleStoryboard.Begin();
                this.mediaElement.Margin = new Thickness(0, 0, 0, 0);
            }
            else 
            {
                this.controlGrid.Opacity = 100;
            }

        }        

        void mediaInfomationGrid_MouseLeave(object sender, MouseEventArgs e)
        {
            this.mediaInfomation_HiddenStoryboard.Begin();            
        }

        void mediaInfomationGrid_MouseEnter(object sender, MouseEventArgs e)
        {
            this.mediaInfomation_VisibleStoryboard.Begin();
        }

        double oldWidth { get; set; }
        double oldHeight { get; set; }

        void btnFullScreen_Click(object sender, RoutedEventArgs e)
        {
            //전체화면 전환
            Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
        }

        void FullScreenChanged(object sender, EventArgs e)
        {
            if (Application.Current.Host.Content.IsFullScreen)
            {
                this.oldWidth = this.Width;
                this.oldHeight = this.Height;

                this.Width = double.NaN;
                this.Height = double.NaN;

                mediaElement.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                this.mediaElement.Margin = new Thickness(0, 30, 0, 0);
                this.controlGrid.Opacity = 0;
            }
            else
            {
                this.Width = this.oldWidth;
                this.Height = this.oldHeight;

                mediaElement.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
                this.mediaElement.Margin = new Thickness(0, 0, 0, 0);
                this.controlGrid.Opacity = 100;
            }
        }


        double oldVolume { get; set; }
        void btnVolume_Click(object sender, RoutedEventArgs e)
        {
            if (this.mediaElement.Volume != 0)
            {
                this.oldVolume = this.mediaElement.Volume;
                this.mediaElement.Volume = 0;
                
            }
            else
            {
                this.mediaElement.Volume = this.oldVolume;
            }
            
        }
        void sliderVolume_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (e.NewValue == 0)
            {
                this.btnVolume.Content = "×";
            }
            else
            {
                this.btnVolume.Content = "♨";
            }
        }
        void mediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            MessageBox.Show("미디어 열기 오류", "오류", MessageBoxButton.OK);                
        }

        void mediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            InitMedia();
        }

        private void InitMedia()
        {
            timer.Stop();
            btnPlay.Content = "▶";
            
            mediaElement.Position = new TimeSpan(0);
            seekBar.Width = 0;
            this.tbSeek.Text = GetMediaPosition();
        }

        void seekGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            seekBar.Width = e.GetPosition(seekGrid).X;

            double selectPercent = seekBar.ActualWidth / seekGrid.ActualWidth;

            mediaElement.Position = new TimeSpan(Convert.ToInt64(mediaElement.NaturalDuration.TimeSpan.Ticks * selectPercent));
        }

        void mediaElement_DownloadProgressChanged(object sender, RoutedEventArgs e)
        {
            this.downloadBar.Width = Convert.ToInt32(seekGrid.ActualWidth * mediaElement.DownloadProgress);
            if (mediaElement.DownloadProgress == 100)
            {
                downloadBar.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            }
        }

        private void SetTimer()
        {
            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(10000);
            timer.Tick += new EventHandler(timer_Tick);            
        }

        void timer_Tick(object sender, EventArgs e)
        {
            this.tbSeek.Text = GetMediaPosition();
            this.seekBar.Width = GetSeekbarPosition();            
        }

        private double GetSeekbarPosition()
        {
            double currentPercent = mediaElement.Position.TotalSeconds / mediaElement.NaturalDuration.TimeSpan.TotalSeconds;
            return Convert.ToInt32(seekGrid.ActualWidth * currentPercent);
        }

        void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine(this.mediaElement.Volume.ToString());
            this.tbSeek.Text = GetMediaPosition();
            TogglePlayToPause();
        }    

        private string GetMediaPosition()
        {
            return string.Format("{0}:{1} / {2}:{3}",
                mediaElement.Position.Minutes.ToString("00"),
                mediaElement.Position.Seconds.ToString("00"),
                mediaElement.NaturalDuration.TimeSpan.Minutes.ToString("00"),
                mediaElement.NaturalDuration.TimeSpan.Seconds.ToString("00"));
        }
                
        void btnStop_Click(object sender, RoutedEventArgs e)
        {
            InitMedia();
            mediaElement.Stop();
        }

        void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            TogglePlayToPause();            
        }

        private void TogglePlayToPause()
        {
            if (btnPlay.Content.Equals("▶"))
            {
                PlayerStart();                
            }
            else
            {
                PlayerPause();
            }
        }

        private void PlayerPause()
        {
            btnPlay.Content = "▶";
            mediaElement.Pause();
        }

        private void PlayerStart()
        {
            btnPlay.Content = "||";
            mediaElement.Play();
            timer.Start();
        }

        void btnGetSource_Click(object sender, RoutedEventArgs e)
        {
            PlayerPause();
            MessageBox.Show("구현 중 ", "퍼가기!", MessageBoxButton.OK);
            PlayerStart();
        }
    }
}
